//
//  LCRadioViewController.m
//  YinYueTai
//
//  Created by CongCong on 15-7-18.
//  Copyright (c) 2015年 CongCong. All rights reserved.
//

#import "LCRadioViewController.h"
#import "CommonHeader.h"

@interface LCRadioViewController ()<UIScrollViewDelegate>
@property (nonatomic) LCRadioModel *radioModel;
@property (nonatomic) UIScrollView *scrollView;
@property (nonatomic) UIPageControl *pageView;
@property (nonatomic) NSTimer *timer;
@property (nonatomic, copy) NSNumber *total;
@property (nonatomic) BOOL isTing;
@end

@implementation LCRadioViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setDrawButton];
    [self fetchWebDataWith:kRadioHeader body:kRadioBody];
    [self creatCollection];
    [self creatRefresh];
    [self registerNib];
}

- (void)registerNib
{
    self.flowLayout.sectionInset = UIEdgeInsetsMake(5, 2, 5, 2);
    self.flowLayout.minimumLineSpacing = 1;
    self.flowLayout.minimumInteritemSpacing = 1;
    [self.collectionView registerNib:[UINib nibWithNibName:@"LCRadioHotCell" bundle:nil] forCellWithReuseIdentifier:@"LCRadioHotCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"LCRaidoAllCell" bundle:nil] forCellWithReuseIdentifier:@"LCRaidoAllCell"];
}
- (void)creatRefresh
{
    __weak typeof(self) weakSelf = self;
    [self.collectionView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        weakSelf.page = 0;
        [weakSelf fetchWebDataWith:kRadioHeader body:kRadioBody];
    }];
    [self.collectionView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        weakSelf.page+=9;
        if (weakSelf.page>=weakSelf.total.integerValue&&weakSelf.total!=nil) {
            [MMProgressHUD show];
            [MMProgressHUD  dismissWithSuccess:@"到底了..."];
            [weakSelf.collectionView footerEndRefreshing];
            return ;
        }
        [weakSelf fetchWebDataWith:kRadioHeaderMore body:[NSString stringWithFormat:kRadioBodyMore,weakSelf.page]];
    }];
}

- (void)initJosnModelWith:(NSDictionary *)dataDict
{
    if (self.isTing) {
        self.isTing = NO;
        NSDictionary *dict = dataDict[@"data"];
        LCMusicInfoModel *listenModel  = [[LCMusicInfoModel alloc]initWithDictionary:dict error:nil];
        LCRdListenViewController *listen = [LCRdListenViewController shareListen];
        listen.playInfoModel = listenModel.playInfo;
        
        LCRdDetailListModel *detail = [[LCRdDetailListModel alloc]init];
        detail.title = listenModel.playInfo.title;
        detail.coverimg = listenModel.playInfo.imgUrl;
        detail.playInfo = listenModel.playInfo;
        detail.musicUrl = listenModel.playInfo.musicUrl;
        NSMutableArray *array = [NSMutableArray arrayWithObjects:detail, nil];
        listen.musicArray = array;
        listen.playInfoModel = listenModel.playInfo;
        listen.index = 0;
        [self.navigationController pushViewController:listen animated:YES];
        return;
    }
    
    if (self.page) {
        NSDictionary *dict = dataDict[@"data"];
        self.total = dict[@"total"];
        NSMutableArray *allArray = [NSMutableArray array];
        for (NSDictionary *allDict in dict[@"list"]) {
            LCRadioAllModel *model = [[LCRadioAllModel alloc]initWithDictionary:allDict error:nil];
            [allArray addObject:model];
        }
        [self.radioModel.alllist addObjectsFromArray:allArray];
        [self.collectionView reloadData];
    }
    else
    {
        NSDictionary *dict = dataDict[@"data"];
        self.radioModel = [[LCRadioModel alloc]initWithDictionary:dict error:nil];
        [self.collectionView reloadData];
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section==0) {
        return self.radioModel.hotlist.count;
    }
    else
    {
        return self.radioModel.alllist.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        LCRadioHotCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LCRadioHotCell" forIndexPath:indexPath];
        LCRadioHostModel *model = self.radioModel.hotlist[indexPath.row];
        [cell showModel:model];
        return cell;
    }
    else
    {
        LCRaidoAllCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LCRaidoAllCell" forIndexPath:indexPath];
        LCRadioAllModel *model = self.radioModel.alllist[indexPath.row];
        [cell showModel:model];
        return cell;
    }
    
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section==0) {
        return CGSizeMake((kScreenSize.width-6)/3, (kScreenSize.width-6)/3);
    }
    else
    {
        return CGSizeMake(kScreenSize.width-4,75);
    }
    return CGSizeMake(0, 0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //点击事件
    if (indexPath.section==0) {
        LCRadioHostModel *model = self.radioModel.hotlist[indexPath.row];
        LCRadiodetailViewController *detail = [[LCRadiodetailViewController alloc]init];
        detail.radioid = model.radioid;
        [self.navigationController pushViewController:detail animated:YES];
    }
    else
    {
        LCRadioAllModel *model = self.radioModel.alllist[indexPath.row];
        LCRadiodetailViewController *detail = [[LCRadiodetailViewController alloc]init];
        detail.radioid = model.radioid;
        [self.navigationController pushViewController:detail animated:YES];
    }
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *header;
    if([kind isEqual:UICollectionElementKindSectionHeader])
    {
        header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Header" forIndexPath:indexPath];
        
    }
    if (indexPath.section==0)
    {
        self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height/662*200)];
        self.scrollView.contentSize = CGSizeMake(kScreenSize.width*self.radioModel.carousel.count, kScreenSize.height/662*200);
        for (int i=0; i<self.radioModel.carousel.count; i++)
        {
            LCRaidoCarouselModel *model = self.radioModel.carousel[i];
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenSize.width*i, 0, kScreenSize.width, kScreenSize.height/662*200)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:[UIImage imageNamed:@"hoder"]];
            
            [self.scrollView addSubview:imageView];
            
            
        }
        self.scrollView.pagingEnabled = YES;
        self.scrollView.bounces = NO;
        self.scrollView.delegate = self;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
        [self.scrollView addGestureRecognizer:tap];
        self.pageView = [[UIPageControl alloc]initWithFrame:CGRectMake(kScreenSize.width-kScreenSize.height/662*80, kScreenSize.height/662*180, kScreenSize.height/662*80, kScreenSize.height/662*20)];
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenSize.height/662*180, kScreenSize.width, kScreenSize.height/662*20)];
        view.backgroundColor = [UIColor grayColor];
        view.alpha = 0.5;
        [header addSubview:view];
        self.pageView.numberOfPages = self.radioModel.carousel.count;
        self.pageView.currentPage = 0;
        [header addSubview:self.scrollView];
        [header addSubview:self.pageView];
        
        if (!self.timer)
        {
             self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];
        }
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, kScreenSize.height/662*200, kScreenSize.width, kScreenSize.height/662*20)];
        label.text = @"全部电台：";
        [header addSubview:label];

    }
        
    return header;
}
- (void)tap
{
    int i = _scrollView.contentOffset.x/kScreenSize.width;
    LCRaidoCarouselModel *model = self.radioModel.carousel[i];
    LCRadiodetailViewController *detail = [[LCRadiodetailViewController alloc]init];
    NSString *string = model.url;
    NSRange range = [string rangeOfString:@"ting"];
    if (range.location==NSNotFound) {
        NSString *raidoID = [string substringFromIndex:12];
        detail.radioid = raidoID;
        
        [self.navigationController pushViewController:detail animated:YES];
    }
    else
    {
        NSString *tingID = [string substringFromIndex:range.location+range.length+1];
        [self fetchWebDataWith:kMusicDetailUrl body:[NSString stringWithFormat:kMusicDetailBody,tingID]];
        self.isTing = YES;
    }
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.pageView.currentPage = scrollView.contentOffset.x/kScreenSize.width;
}
- (void)changeTimeAtTimedisplay
{
    CGPoint p;
    if (_scrollView.contentOffset.x==kScreenSize.width*(self.radioModel.carousel.count-1)) {
        p = CGPointMake(0, 0);
    }
    else
    {
        p = CGPointMake(_scrollView.contentOffset.x+kScreenSize.width, 0);
    }
    [UIView animateWithDuration:1 animations:^{
        _scrollView.contentOffset = p;
    }];
    
    int i = _scrollView.contentOffset.x/kScreenSize.width;
    self.pageView.currentPage = i;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section==0) {
       return CGSizeMake(kScreenSize.width, kScreenSize.height/662*220);
    }
    
    return CGSizeMake(0, 0);
}















@end
